import http from '@/utils/request'
import type { ApiResponse, PaginationResponse } from '@/types'

export interface Work {
  id: number
  artistId: number
  title: string
  duration?: string
  description?: string
  releaseDate?: string
  isRepresentative: boolean
  audioUrl?: string
  createdAt: string
  updatedAt: string
  artist?: {
    id: number
    name: string
    avatar?: string
  }
}

export interface CreateWorkData {
  artistId: number
  title: string
  duration?: string
  description?: string
  releaseDate?: string
  isRepresentative?: boolean
}

export interface UpdateWorkData {
  title?: string
  duration?: string
  description?: string
  releaseDate?: string
  isRepresentative?: boolean
}

export interface WorkListParams {
  page?: number
  limit?: number
  artistId?: number
  search?: string
  isRepresentative?: boolean
}

/**
 * 获取作品列表
 */
export const getWorkList = (params?: WorkListParams): Promise<ApiResponse<PaginationResponse<Work>>> => {
  return http.get('/admin/works', { params })
}

/**
 * 获取作品详情
 */
export const getWorkDetail = (id: number): Promise<ApiResponse<Work>> => {
  return http.get(`/admin/works/${id}`)
}

/**
 * 创建作品
 */
export const createWork = (data: CreateWorkData): Promise<ApiResponse<Work>> => {
  return http.post('/admin/works', data)
}

/**
 * 更新作品
 */
export const updateWork = (id: number, data: UpdateWorkData): Promise<ApiResponse<Work>> => {
  return http.put(`/admin/works/${id}`, data)
}

/**
 * 删除作品
 */
export const deleteWork = (id: number): Promise<ApiResponse<null>> => {
  return http.delete(`/admin/works/${id}`)
}

/**
 * 批量删除作品
 */
export const batchDeleteWorks = (ids: number[]): Promise<ApiResponse<{ deletedCount: number }>> => {
  return http.delete('/admin/works/batch', { data: { ids } })
}

/**
 * 获取作品统计信息
 */
export const getWorkStatistics = (): Promise<ApiResponse<{
  totalWorks: number
  representativeWorks: number
  worksByArtist: Array<{
    artistId: number
    artistName: string
    artistAvatar?: string
    workCount: number
  }>
  recentWorks: Work[]
}>> => {
  return http.get('/admin/works/statistics/overview')
}

/**
 * 获取艺人的作品列表
 */
export const getArtistWorks = (artistId: number, params?: { page?: number; limit?: number }): Promise<ApiResponse<PaginationResponse<Work>>> => {
  return http.get(`/admin/works/artist/${artistId}`, { params })
}

/**
 * 上传作品音频
 */
export const uploadWorkAudio = (id: number, file: File): Promise<ApiResponse<Work>> => {
  const formData = new FormData()
  formData.append('workAudio', file)
  return http.post(`/admin/works/${id}/audio`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 删除作品音频
 */
export const deleteWorkAudio = (id: number): Promise<ApiResponse<Work>> => {
  return http.delete(`/admin/works/${id}/audio`)
}
